package com.gec.teams.wechat.mongodb;

import com.gec.teams.wechat.pojo.entity.MessageRefEntity;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/25 11:04
 */
@Repository
public class MessageRefDao {
    @Autowired
    private MongoTemplate mongoTemplate;


    //插入ref数据
    public String insert(MessageRefEntity messageRef){
        messageRef = mongoTemplate.save(messageRef);
        return messageRef.get_id();
    }

    //查询用户未读的消息
    public long searchUnreadCount(int userId){
        Query query = new Query();
        query.addCriteria(Criteria.where("readFlag").is(false).and("receiverId").is(userId));
        long count = mongoTemplate.count(query, MessageRefEntity.class);
        return count;
    }

    //查询最新消息
    public long searchLastCount(int userId){
        Query query = new Query();
        query.addCriteria(Criteria.where("lastFlag").is(true).and("receiverId").is(userId));
        Update update = new Update();
        update.set("lastFlag",false);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update,  "message_ref");
        long count = updateResult.getMatchedCount();
        return count;
    }
    //更新消息为已读
    public  long updateReadFlag(String id){
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("readFlag",true);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update,  "message_ref");
        long row = updateResult.getMatchedCount();
        return row;
    }
    //删除记录
    public long deleteMessageRef(String id){
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        DeleteResult deleteResult = mongoTemplate.remove(query, "message_ref");
        long deletedCount = deleteResult.getDeletedCount();
        return deletedCount;
    }
    //通过用户id删除消息记录
    public long deleteUserMessageRef(int userId){
        Query query = new Query();
        query.addCriteria(Criteria.where("receiverId").is(userId));
        DeleteResult messageRef = mongoTemplate.remove(query, "message_ref");
        long deletedCount = messageRef.getDeletedCount();
        return deletedCount;
    }
}
